<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>编辑自由拼团线路</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="__PUBLIC__/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="__PUBLIC__/font-awesome/css/font-awesome.min.css" media="all" />
    <link rel="stylesheet" href="__CSS__/admin.css"  media="all">
    <script src="{$Think.config.httpFlag}{$Think.config.google_map_url}" async="async"></script>
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
    <style>
        #admin dl{z-index:99999;}
        .pro_li,.trip_li{
            border-bottom: 1px dashed #efefef;
        }
        .carAndTicketCurrency{
            text-align: left;
            padding-left:0;
            padding-right:0;
            position: absolute;
            top: 10px;
            left: 520px;
        }
        .busySeason{
            color:red;
        }
    </style>

</head>
<body>
<div style="margin-top: 20px;">
</div>
<form class="layui-form" id="admin">
    <!--标题-->
    <div class="layui-form-item">
        <label class="layui-form-label">标题</label>
        <div class="layui-input-block" style="max-width:620px;">
            <input name="title" lay-verify="title" autocomplete="off" placeholder="请输入标题" class="layui-input" type="text" {notempty name="$info.title"}value="{$info.title}"{/notempty}>
        </div>
    </div>
    <!--城市-->
    <div class="layui-form-item">
        <div class="layui-form-item">
            <label class="layui-form-label">城市</label>
            <div class="layui-input-inline" style="position: relative;width: 400px">
                <select id="trip_class" name="city_id" lay-filter="addtrips_class" lay-verify="required" lay-search>
                    <option selected value="">请选择</option>
                    <!--<option selected value="999999">全部</option>-->
                    <!--<option value="8888">美国</option>-->
                    <!--<option value="7777">加拿大</option>-->
                    {volist name="city" id="vo"}
                    <option value="{$vo.id}" {notempty name='info'}{if $vo.id==$info.city_id}selected{/if}{/notempty}>{$vo.name}</option>
                    {/volist}
                </select>
            </div>
        </div>
    </div>
    <!--天数-->
    <div class="layui-form-item">
        <div class="layui-form-item">
            <label class="layui-form-label">出行天数</label>
            <div class="layui-input-inline" style="position: relative;width: 400px">
                <input type="text" autocomplete="off" value="{notempty name='$info.days'}{$info.days}{/notempty}" name="days" class="layui-input" lay-verify="required">
            </div>
        </div>
    </div>

    <!--拼团简介-->
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">拼团简介</label>
        <div class="layui-input-block" style="max-width:620px;">
            <textarea placeholder="请输入拼团简介" class="layui-textarea" name="description">{notempty name="$info.description"}{$info.description}{/notempty}</textarea>
        </div>
    </div>
    <!--关联产品-->
    <div class="layui-form-item" style="position: relative">
        <label class="layui-form-label">关联行程产品</label>
        <div class="layui-input-inline">
            <input type="text" name="trip_name" lay-verify="title" value="{notempty name='info.trip_id'}{$info.trip_name}{/notempty}" autocomplete="off" placeholder="请输入产品名称" class="layui-input" lay-verify="required" style="width:620px;">
            <input type="hidden" name="trip_id" lay-verify="trip_id" value="{notempty name='info.trip_id'}{$info.trip_id}{/notempty}" >
        </div>
        <div class="selectTripList layui-anim layui-anim-upbit layui-input" style="position: absolute;width: 400px;z-index: 2;top: 40px;left: 110px;display: inline-block;height:auto;display: none;">
            <dl id="selectTripList" class="selectTripList layui-anim layui-anim-upbit" style="padding:8px;line-height: 35px;max-height:300px;overflow:auto;display: none">
                <dd data-id="0" class="layui-select-tips trip_li" style="color:#999">不选择poi</dd>
            </dl>
            </dl>
        </div>
    </div>
    <!--权重排序-->
    <div class="layui-form-item">
        <div class="layui-form-item">
            <label class="layui-form-label">权重</label>
            <div class="layui-input-inline" style="position: relative;width: 400px">
                <input type="text" autocomplete="off" value="{notempty name='$info.sort_num'}{$info.sort_num}{/notempty}{empty name='$info.sort_num'}1{/empty}" name="sort_num" class="layui-input" lay-verify="required">
            </div>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-form-item">
            <label class="layui-form-label">禁用/启用</label>
            <div class="layui-input-inline" style="position: relative;width: 400px">
                <input type="radio" name="is_use" value="1" {if isset($info['is_use'])}{if $info.is_use==1}checked=""{/if}{else}checked=""{/if} title="启用" >
                <input type="radio" name="is_use" value="0" {if isset($info['is_use'])}{if $info.is_use==0}checked=""{/if}{/if} title="禁用" >
            </div>
        </div>
    </div>
    <div class="layui-upload" id="upload-thumb">
        <label class="layui-form-label">缩略图</label>
        <button type="button" class="layui-btn" id="thumb">上传图片</button>
        <div class="layui-upload-list">
            <label class="layui-form-label"></label>
            <img class="layui-upload-img" id="demo1" width="150" height="150" {notempty name="$info.img"}src="{$info.img}"{/notempty}>{notempty name="$info.img"}<input type="hidden" name="img" value="{$info.img}">{/notempty}
            <p id="demoText"></p>
        </div>
    </div>
    {notempty name="$info"}
    <input type="hidden" name="id" value="{$info.line_id}">
    {/notempty}
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="admin">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<script src="__PUBLIC__/layui/layui.js"></script>
<script src="__PUBLIC__/jquery/jquery.min.js"></script>
<script>
    //地图功能
    var from_address = null;
    var to_address = null;
    geocoder = new google.maps.Geocoder();
    //初步获取地址
    function Address(obj,address_type) {
        var address = document.getElementById(obj).value;
        var addressbox="";
        //地址解析
        geocoder.geocode({
            'address' : address
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                for(var i in results){
                    if(i>4){
                        break;
                    }
                    addressbox+="<span>"+results[i].formatted_address+"</span>";
                }
                $(".addressbox_"+address_type).show();
                $(".addressbox_"+address_type).html(addressbox);
            }
        })
    }

    $("input[name=from_address]").on('input',function(){
        Address('from_address','from')
    })
    $("input[name=to_address]").on('input',function(){
        Address('to_address','to')
    })
    $(".addressbox_from").on("click","span",function(){
        var _that = this;
        var address = $(_that).text();
        $(_that).parent().prev().val(address);
        //地址解析
        geocoder.geocode({
            'address' : address
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                console.log(results);
                //设置地址的同时需要获取货币单位
                from_address = formattedAddressToOrder(results[0],true);
                $(_that).parent().hide();
                $(_that).parent().next().val(from_address);
            }

        })
    })
    $(".addressbox_to").on("click","span",function(){
        var _that = this;
        var address = $(_that).text();
        $(_that).parent().prev().val(address);
        //地址解析
        geocoder.geocode({
            'address' : address
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                console.log(results);
                to_address = formattedAddressToOrder(results[0]);
                $(_that).parent().hide();
                $(_that).parent().next().val(to_address);
            }

        })
    })

    //传入谷歌地址的数据结构
    function formattedAddressToOrder(address,setCurrency=false)
    {
        if(setCurrency){
            var last_index = address.address_components.length;
            var short_name = address.address_components[last_index-1].short_name;
            console.log(short_name);
            if(short_name=="CA"){
                $("input[name=currency]").val("CAD");
                $("input[name=currency_name]").val("加元");
                $(".carAndTicketCurrency").text("加元");
            }else if(short_name=="US"){
                $("input[name=currency]").val("USD");
                $("input[name=currency_name]").val("美元");
                $(".carAndTicketCurrency").text("美元");
            }else{
                $("input[name=currency]").val("CNY");
                $("input[name=currency_name]").val("人民币");
                $(".carAndTicketCurrency").text("人民币");
            }
        }
        var location = address.geometry.location.toString();
        location = location.substring(1,location.indexOf(")"));
        var location_arr = location.split(",");
        var formatt = {
            "arbitrary":{
                "geocoded":{
                    "name":address.address_components[0].long_name,
                    "addr":address.formatted_address,
                    "lat":parseFloat(location_arr[0]),
                    "lng":parseFloat(location_arr[1]),
                    "gid":address.place_id,
                }
            }
        };
        return JSON.stringify(formatt);
    }
</script>
<script>
    layui.use('upload', function(){
        var upload = layui.upload;
        //执行实例

        var uploadInst = upload.render({
            elem: '#thumb' //绑定元素
            ,url: "{:url('common/upload')}" //上传接口
            ,data:{use:'grouptours_thumb'}
            ,accept: 'images'
            ,done: function(res){
                //上传完毕回调
                layer.closeAll('loading');
                if(res.code == 2) {
                    $('#demo1').attr('src',res.src);
                    $('#upload-thumb').append('<input type="hidden" name="img" value="'+ res.src +'">');
                } else {
                    layer.msg(res.msg);
                }
            }
            ,error: function(){
                //请求异常回调
                //演示失败状态，并实现重传
                layer.closeAll('loading');
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }
            ,before:function () {
                layer.load(2);
            }
        });
    });
</script>
<script>
    layui.use(['layer', 'form'], function() {
        var layer = layui.layer,
            $ = layui.jquery,
            form = layui.form;
        $(window).on('load', function() {
            form.on('submit(admin)', function(data) {
                $.ajax({
                    url:"{:url('admin/grouptoursline/editfree')}",
                    data:$('#admin').serialize(),
                    type:'post',
                    async: false,
                    success:function(res) {
                        if(res.code == 1) {
                            layer.msg(res.msg);
                            setTimeout(function(){
                                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                                parent.layer.close(index); //再执行关闭
                            },1000)
                        } else {
                            layer.msg(res.msg);
                        }
                    }
                })
                return false;
            });
        });
        //通过城市和包车类型获取派单价
        var cityId = carType = subType = '';
        var days = 0;
        {notempty name='info.city_id'}cityId={$info.city_id};{/notempty}
        {notempty name='info.carType'}carType={$info.carType};{/notempty}
        {notempty name='info.subType'}subType={$info.subType};{/notempty}
        {notempty name='info.days'}days={$info.days};{/notempty}
        function getCarPriceByCarTypeAndCity(cityId,carType,subType,days)
        {
            console.log(cityId,carType,subType,days)
            if(cityId=='' || cityId==undefined) return false;
            if(carType=='' || carType==undefined) return false;
            if(subType=='' || subType==undefined) return false;
            if(days==0 || days==undefined) return false;
            var loading = layer.load(2);
            $.post('/admin/grouptoursline/getCarPriceBySubTypeAndCity',{cityId:cityId,carType:carType,subType:subType},function(res){
                layer.close(loading);
                if(res.code>0){
                    //获取用车成本
                    var idleCarPrice = res.data.idleCarPrice || 0;
                    var busyCarPrice = res.data.busyCarPrice || 0;
                    $('input[name=carPrice]').val(days*idleCarPrice);
                    $('input[name=busyCarPrice]').val(days*busyCarPrice);
                    changePersonPrice(days*idleCarPrice);
                    changeBusyPersonPrice(days*busyCarPrice);
                }else{
                    layer.msg(res.msg);
                }
            },'json')
        }
        //淡季派单价
        $('input[name=carPrice]').change(function(){
            var val = parseFloat($(this).val());
            changePersonPrice(val);
        })
        //旺季派单价
        $('input[name=busyCarPrice]').change(function(){
            var val = parseFloat($(this).val());
            changeBusyPersonPrice(val);
        })
        //计算淡季单人售价
        function changePersonPrice(carPrice)
        {
            var person_price = Math.ceil(carPrice*1.05/2);
            $('input[name=person_price]').val(person_price);
        }
        //计算淡季单人售价
        function changeBusyPersonPrice(busyCarPrice)
        {
            var busy_person_price = Math.ceil(busyCarPrice*1.05/2);
            $('input[name=busy_person_price]').val(busy_person_price);
        }
        form.on('select(addtrips_class)', function(data){
            cityId = data.value;
            getCarPriceByCarTypeAndCity(cityId,carType,subType,days);
        });
        form.on('select(carType)', function(data){
            carType = data.value;
            getCarPriceByCarTypeAndCity(cityId,carType,subType,days);
        });
        form.on('select(subType)', function(data){
            subType = data.value;
            getCarPriceByCarTypeAndCity(cityId,carType,subType,days);
        });
        $('input[name=days]').change(function(){
            days = $(this).val()
            getCarPriceByCarTypeAndCity(cityId,carType,subType,days);
        })
    });
</script>

<script type="text/javascript">
    layui.use(['layer','form'], function() {
        var layer = layui.layer,
            form = layui.form;

        $(window).on('load', function () {

        })
    });
    var proli_show = tripli_show = false;
    //初始化poi列表
    $("input[name=product_name]").focus(function(){
        proli_show = true;
        $(".selectProList").show();
    })
    $('input[name=product_name]').bind('input propertychange', function() {
        //进行相关操作
        var key = $(this).val();
        $("input[name=product_id]").val(0);
        getProList(key)
    });

    function getProList(key)
    {
        $.post("/admin/grouptoursline/searchProduct",{key:key},function(data){
            var list = data.data;
            if(list.length>0){
                $("#selectProList dd").not(":first").remove();
                var str = "";
                $.each(list,function(i,v){
                    str += "<dd class='pro_li' data-id='"+v.goods_id+"'>"+v.goods_name+"</dd>";
                })
                $("#selectProList").append(str);
            }
        },'json')
    }
    $(document).on("click",'.pro_li',function(){
        var content= $(this).text();
        var id= $(this).attr('data-id');
        $('input[name=product_id]').val(id)
        if(id==0){
            $('input[name=product_name]').val('')
        }else{
            $('input[name=product_name]').val(content)
        }
        proli_show = false;
        $(".selectProList").hide();
    })

    $(document).mouseup(function(e){
        if(proli_show){
            var _con = $('.pro_li,input[name=product_name]');   // 设置目标区域
            if(!_con.is(e.target) && _con.has(e.target).length === 0){ // Mark 1
                $(".selectProList").hide();
            }
        }
        var search_id = $("input[name=product_id]").val();
        if(search_id=='' || search_id==0 || search_id==undefined){
            $("input[name=product_name]").val('');
        }

    });
    //产品配置
    //初始化poi列表
    $("input[name=trip_name]").focus(function(){
        tripli_show = true;
        $(".selectTripList").show();
    })
    $('input[name=trip_name]').bind('input propertychange', function() {
        //进行相关操作
        var key = $(this).val();
        $("input[name=trip_id]").val(0);
        getTripList(key)
    });
    function getTripList(key)
    {
        $.post("/admin/grouptoursline/searchTrip",{key:key},function(data){
            var list = data.data;
            if(list.length>0){
                $("#selectTripList dd").not(":first").remove();
                var str = "";
                $.each(list,function(i,v){
                    str += "<dd class='trip_li' data-id='"+v.id+"'>"+v.name+"</dd>";
                })
                $("#selectTripList").append(str);
            }
        },'json')
    }
    $(document).on("click",'.trip_li',function(){
        var content= $(this).text();
        var id= $(this).attr('data-id');
        $('input[name=trip_id]').val(id)
        if(id==0){
            $('input[name=trip_name]').val('')
        }else{
            $('input[name=trip_name]').val(content);
            //更新产品简介
            $.post("/admin/grouptoursline/getSummaryTrip",{trip_id:id},function(data){
                if(data.code==1){
                    $('textarea[name=toursLineTitle]').val(data.data);
                }
            },'json')
        }
        proli_show = false;
        $(".selectTripList").hide();
    })

    $(document).mouseup(function(e){
        if(tripli_show){
            var _con = $('.trip_li,input[name=trip_name]');   // 设置目标区域
            if(!_con.is(e.target) && _con.has(e.target).length === 0){ // Mark 1
                $(".selectTripList").hide();
            }
        }
        var search_id = $("input[name=trip_id]").val();
        if(search_id=='' || search_id==0 || search_id==undefined){
            $("input[name=trip_name]").val('');
        }

    });
</script>
<!-- 配置文件 -->
<script type="text/javascript" src="__PUBLIC__/ueditor/ueditor.config.js"></script>
<!-- 编辑器源码文件 -->
<script type="text/javascript" src="__PUBLIC__/ueditor/ueditor.all.js"></script>
<!-- 实例化编辑器 -->
<script type="text/javascript">
    //拼团详情暂时隐藏
    $(function(){
        // var ue2 = UE.getEditor('desc',{
        //     initialFrameHeight: 100,
        //     initialFrameWidth: 600,
        //     toolbars:[
        //         [ 'source'],
        //         ['bold', 'italic', 'underline', 'fontborder', 'strikethrough']
        //     ]
        // });
    })
</script>
</body>
</html>
